import type { WatchStopHandle } from "vue";
import { nextTick, reactive, ref, watchEffect } from "vue";
import { usePlayAudio } from "../common/playAudio";
const { playAudio } = usePlayAudio();


// 定义单词的接口，包含每个单词的状态、文本和位置等信息
interface Word {
    text: string;
    isActive: boolean;
    userInput: string;
    incorrect: boolean;
    end: number;
    isEnd: boolean;
    start: number;
    position: number;
    id: number;
}
interface KeyboardInputOptions {
    useSpaceSubmitAnswer?: {
        enable: boolean;
        rightCallback?: () => void;
        errorCallback?: () => void;
    };
}
// 输入选项接口，包含源文本、获取和设置光标位置的回调函数等
interface InputOptions {
    source: () => string;
    setInputCursorPosition: (position: number) => void;
    getInputCursorPosition: () => number;
    inputChangedCallback?: (e: KeyboardEvent) => void;
}

// 模式枚举，用于标记不同的编辑状态
enum Mode {
    Input = "input",        // 正常输入模式
    Fix = "fix",            // 错误单词修正模式提交
    Fix_Input = "fix-input",// 错误单词修正模式下输入
}

// 分隔符，默认是空格
const separator = " ";
const inputValue = ref("");  // 用于存储用户输入的内容



// 清空用户输入
export function clearQuestionInput() {
    inputValue.value = "";
}
// 检查字符串是否为一个有效的单词
export function isWord(content: string) {
    return /[a-zA-Z0-9]/.test(content);
}
const mode = ref<Mode>(Mode.Input); // 当前模式，默认是输入模式
let currentEditWord: Word;         // 当前正在编辑的单词
const userInputWords = reactive<Word[]>([]); // 用于存储所有单词的用户输入状态
const userInputIsEnd = ref(false);
let stopWatchEffect: WatchStopHandle; // 用于停止watchEffect的回调
// 输入逻辑的组合式函数，接受一些回调和设置函数作为参数
export function useInput({
    source,
    setInputCursorPosition,
    getInputCursorPosition,
    inputChangedCallback,

}: InputOptions) {

    // 初始化函数
    function initialize() {
        stopWatchEffect && stopWatchEffect();  // 清除之前的 watchEffect
        mode.value = Mode.Input;  // 重置为输入模式
        userInputWords.length = 0; // 清空单词数组
        setupUserInputWords();    // 设置用户输入的单词
        updateActiveWord(getInputCursorPosition()); // 更新激活的单词

        
    }

    // 设置输入值并同步到用户输入单词
    function setInputValue(val: string) {
        inputValue.value = val;
        resetAllWordUserInput();    // 重置所有单词的用户输入
        inputSyncUserInputWords();  // 同步用户输入到单词状态
        updateActiveWord(val ? getInputCursorPosition() : 0);  // 更新激活单词
    }

    // 创建一个单词对象
    function createWord(word: string, id: number) {
        return reactive({
            text: word,
            isActive: false,      // 默认为不激活
            userInput: "",        // 初始用户输入为空
            incorrect: false,     // 默认为正确
            start: 0,             // 单词开始位置
            end: 0,               // 单词结束位置
            position: 0,          // 单词在输入中的位置
            id,
        } as Word);
    }
    // 设置用户输入的单词
    function setupUserInputWords() {
        stopWatchEffect = watchEffect(() => {
            userInputIsEnd.value = false; //每次清空结束状态
            resetUserInputWords();  // 每次重新设置时清空用户输入
            const english = source();  // 获取源文本
            let inputWordIndex = 0;
            playAudio(english); //播放音频
            english.split(separator).forEach((text, index) => {
                if (isWord(text)) {
                    const word = createWord(text, index);
                    userInputWords[inputWordIndex] = word;
                    inputWordIndex === 0 && (userInputWords[0].isActive = true); // 激活第一个单词
                    inputWordIndex++;
                }
            });
        });
    }
    function findModeInput() {
        return mode.value === Mode.Input;
    }
    // 同步用户输入到单词状态
    function userInputWordsSyncInput() {
        inputValue.value = userInputWords
            .map(({ userInput }) => userInput)  // 获取所有单词的用户输入
            .join(separator);  // 用空格连接
    }

    // 同步用户输入的单词状态
    function inputSyncUserInputWords() {
        let position = 0;
        inputValue.value.split(separator).forEach((input, index) => {
            if (userInputWords[index]) {
                userInputWords[index].userInput = input;
                userInputWords[index].start = position;
                userInputWords[index].end = position + input.length;
            }
            position += input.length + 1; // 加1是为了空格
        });
    }

    // 重置所有单词的用户输入
    function resetAllWordUserInput() {
        userInputWords.forEach((word) => {
            word.userInput = "";
        });
    }

    // 重置所有单词的激活状态
    function resetAllWordActive() {
        userInputWords.forEach((word) => {
            word.isActive = false;
        });
    }

    // 更新激活的单词
    function updateActiveWord(position: number) {
        resetAllWordActive();
        for (let i = 0; i < userInputWords.length; i++) {
            const word = userInputWords[i];
            if (position >= word.start && position <= word.end) {
                word.isActive = true;
                break;
            }
        }
    }

    // 检查单词是否都正确
    function checkWordCorrect() {
        return userInputWords.every((w) => !w.incorrect);
    }


    // 标记错误的单词
    function markIncorrectWord() {
        userInputWords.forEach((word, index) => {
            //            word.incorrect = word.userInput !== word.text.toLocaleLowerCase();  // 比较大小写
            word.incorrect = word.userInput.toLowerCase() !== word.text.toLowerCase();  // 比较大小写
        });
    }

    // 判断最后一个单词是否是活跃的
    function lastWordIsActive() {
        let len = userInputWords.length;
        return userInputWords[len - 1].isActive;
    }
    // 查找下一个错误单词
    function findNextIncorrectWordNew() {
        if (!currentEditWord) return;
        const wordIndex = userInputWords.findIndex((w) => w.id === currentEditWord.id);
        for (let i = wordIndex + 1; i < userInputWords.length; i++) {
            if (userInputWords[i].incorrect) {
                return userInputWords[i];
            }
        }
    }
    // 获取第一个错误单词
    function getFirstIncorrectWord() {
        return userInputWords.find((w) => w.incorrect);
    }
    // 清空下一个错误单词的输入
    async function clearNextIncorrectWord(word: Word) {
        word.userInput = "";
        currentEditWord = word;
        userInputWordsSyncInput();
        await nextTick();
        setInputCursorPosition(word.start);
        updateActiveWord(word.start);
    }

    // 提交答案，调用相应的回调
    function submitAnswer(correctCallback?: () => void, wrongCallback?: () => void) {
        if (mode.value === Mode.Fix) return;
        resetAllWordActive();
        markIncorrectWord();

        if (checkWordCorrect()) {
            mode.value = Mode.Input;
            userInputIsEnd.value = true;
            correctCallback?.();
            //inputValue.value = "";
        } else {
            mode.value = Mode.Fix;
            wrongCallback?.();
        }
    }

    // 修复第一个错误单词
    async function fixFirstIncorrectWord() {
        if (mode.value === Mode.Fix) {
            mode.value = Mode.Fix_Input;
            await clearNextIncorrectWord(getFirstIncorrectWord()!);
        }
    }

    // 修复下一个错误单词
    async function fixNextIncorrectWord() {
        if (mode.value === Mode.Fix_Input) {
            await clearNextIncorrectWord(findNextIncorrectWordNew()!);
        }
    }

    // 修复错误单词
    async function fixIncorrectWord() {
        if (mode.value === Mode.Fix) {
            await fixFirstIncorrectWord();
        } else if (mode.value === Mode.Fix_Input) {
            await fixNextIncorrectWord();
        }
    }

    // 判断当前编辑的单词是否为空
    function isEmptyOfCurrentEditWord() {
        return currentEditWord.userInput.length <= 0;
    }

    // 查找上一个错误单词
    function findPreviousIncorrectWord() {
        if (!currentEditWord) return;
        const wordIndex = userInputWords.findIndex((w) => w.id === currentEditWord.id);
        for (let i = wordIndex - 1; i >= 0; i--) {
            if (userInputWords[i].incorrect) {
                return userInputWords[i];
            }
        }
    }

    // 激活上一个错误单词
    async function activePreviousIncorrectWord() {
        const previousIncorrectWord = findPreviousIncorrectWord();
        if (previousIncorrectWord) {
            currentEditWord = previousIncorrectWord;
            await nextTick();
            updateActiveWord(previousIncorrectWord.end);
            setInputCursorPosition(previousIncorrectWord.end);
        }
    }

    // 处理空格提交答案的逻辑
    function handleSpaceSubmitAnswer(
        useSpaceSubmitAnswer: KeyboardInputOptions["useSpaceSubmitAnswer"],
    ) {
        if (useSpaceSubmitAnswer?.enable) {
            submitAnswer(
                useSpaceSubmitAnswer?.rightCallback,
                useSpaceSubmitAnswer?.errorCallback,
            );
        }
    }

    // 处理键盘输入事件
    function handleKeyboardInput(e: KeyboardEvent, options?: KeyboardInputOptions) {
        // 禁止方向键移动
        if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(e.code)) {
            e.preventDefault();
            return;
        }

        // 按下Enter键触发答案提交
        if (e.code === "Enter") {
            e.preventDefault();
            e.stopPropagation();
            handleSpaceSubmitAnswer(options?.useSpaceSubmitAnswer);
            return;
        }
        // Fix_Input/Input 下启用空格提交 且 在最后一个单词位置
        if (mode.value !== Mode.Fix && e.code === "Space" && lastWordIsActive()) {
            e.preventDefault();
            e.stopPropagation();
            handleSpaceSubmitAnswer(options?.useSpaceSubmitAnswer);
            return;
        }

        // Fix 模式下 允许用户按下任意键去修改第一个错误的单词
        if (mode.value === Mode.Fix) {
            if (e.code === "Space" || e.code === "Backspace") {
                e.preventDefault();
            }
            fixFirstIncorrectWord();
            inputChangedCallback?.(e);
            return;
        }

        // Fix_Input 下启用空格提交 且 在最后一个错误单词位置
        if (mode.value === Mode.Fix_Input && e.code === "Space" && !findNextIncorrectWordNew()) {
            console.log('2')
            e.preventDefault();
            e.stopPropagation();
            handleSpaceSubmitAnswer(options?.useSpaceSubmitAnswer);
            return;
        }

        // Fix_Input 模式下当前编辑单词为空时，启用退格删除上一个错误单词
        if (mode.value === Mode.Fix_Input && e.code === "Backspace" && isEmptyOfCurrentEditWord()) {
            console.log('1')
            e.preventDefault();
            activePreviousIncorrectWord();
            inputChangedCallback?.(e);
            return;
        }

        // 空格修复单词
        if (mode.value !== Mode.Input && e.code === "Space") {
            e.preventDefault();
            fixIncorrectWord();
            inputChangedCallback?.(e);
            return;
        }

        inputChangedCallback?.(e); // 调用输入变化的回调
    }

    // 重置用户输入的单词
    function resetUserInputWords() {
        mode.value = Mode.Input;
        inputValue.value = "";
        userInputWords.splice(0, userInputWords.length); // 清空用户输入的单词
    }
    function findWordById(id: number) {
        return userInputWords.find((word) => word.id === id);
    }
    return {
        inputValue,
        userInputWords,
        userInputIsEnd,
        findModeInput,
        findWordById,
        submitAnswer,
        setInputValue,
        activePreviousIncorrectWord,
        handleKeyboardInput,
        fixIncorrectWord,
        fixFirstIncorrectWord,
        resetUserInputWords,
        initialize,
    };
}
